package com.lt.test.provider.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.lt.test.api.KtCommonService;
import com.lt.test.api.UserService;
import com.lt.test.common.exception.CustomException;
import com.lt.test.common.util.DateUtil;
import com.lt.test.common.util.StringUtils;
import com.lt.test.provider.dao.*;
import com.lt.test.entity.DO.UserDO;
import com.lt.test.entity.DTO.PageDTO;
import com.lt.test.provider.mapper.KtCommonMapper;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@Service(version = "1.0.0")
public class KtCommonServiceImpl implements KtCommonService{
	
	 @Autowired
	 KtZoneDao ktZoneDao;
	 
	 @Autowired
	 KtOrgDao ktOrgDao;
	 
	 @Autowired
	 KtUserDao ktUserDao;
	 
	 @Autowired
	 private UserService userService;
	 
	 @Autowired
	 private PlatformUserDao platformUserDao;
	 
	 @Autowired
	 private DShopDao dshopDao;

	 @Autowired
	 KtCommonMapper ktCommonMapper;
	 
	 
	 
//	 @Autowired
//	 com.combinedpay.clouderp.sys.api.UserService clouderpUserService;
	 
	 
	 public static boolean DEV_DEBUG = false;
		
		static{
			try {
				Properties prop = new Properties();
				InputStream in = KtCommonServiceImpl.class.getClassLoader().getResourceAsStream("dev.properties");
				prop.load(in);
				DEV_DEBUG = Boolean.parseBoolean(prop.getProperty("DEV_DEBUG"));
				
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	 
	@Override
	public List<Map<String, Object>> getSubZone(Map parameter) {
		// TODO Auto-generated method stub
		 String parentId = parameter.get("parentId") == null ? "0" : parameter.get("parentId").toString();
		 
			return ktZoneDao.getSubZone(parentId);
	}

	@Override
	public PageDTO<Map<String, Object>> getZoneListByPage(Integer page, Integer pageSize, String filters) {
		// TODO Auto-generated method stub
		Long beginNum = (long) ((page - 1) * pageSize + 1);
		Long endNum = beginNum + pageSize - 1;

		List<Map<String,Object>> typeList = null;
		int recordCount = 0;
		String zoneName = null;
		String parentId = null;
		String state = null;
		if(filters != null && !filters.trim().equals("")) {
			JSONObject jsonObject = JSONObject.fromObject(filters);
			JSONArray jsonArray = (JSONArray) jsonObject.get("rules");
			for(int i = 0; i < jsonArray.size(); i++) {
				JSONObject result = (JSONObject) jsonArray.get(i);
				if("zoneName".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))){
					zoneName =  result.getString("data");
				}
				if("parentId".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))){
					parentId =  result.getString("data");
				}
				if("state".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))){
					state =  result.getString("data");
				}
			}
		}
		
		typeList = ktZoneDao.getZoneListByPage(parentId,zoneName,state,beginNum,endNum);
		recordCount = Integer.valueOf(ktZoneDao.getZoneListSize(parentId,zoneName,state).get("total").toString());
		PageDTO<Map<String,Object>> result = new PageDTO<>(page, pageSize, typeList, recordCount);
		return result;
	}

	@Override
	public void saveZone(Map parameter) {
		// TODO Auto-generated method stub
		String id = parameter.get("id") == null ? null : parameter.get("id").toString();
		String parentId =StringUtils.isNullOrEmpty(parameter.get("parentId")) ? "0": parameter.get("parentId").toString();
		if(!StringUtils.isNullOrEmpty(id)){
			//检查parentid 是否相同
				parameter.put("stateTime", new Date());
				ktZoneDao.update(parameter);
		}else{
			String typeId = null;
			Map maxData = ktZoneDao.getMaxData(parentId);
			if(maxData == null){
				if(parentId.equals("0")){
					typeId = "01";
					parameter.put("parentId", "0");
					parameter.put("zoneCode", typeId);
				}else{
					typeId = parentId+"01";
					parameter.put("parentId", parentId);
					parameter.put("zoneCode", typeId);
				}
				
			}else{
				String maxTypeId = maxData.get("zoneCode").toString();
				
				String maxTypeIdEndNum = "0";
				if(parentId.equals("0")){
					parameter.put("parentId", "0");
					maxTypeIdEndNum = maxTypeId.substring(0,maxTypeId.length());
				}else{
					parameter.put("parentId", parentId);
					maxTypeIdEndNum = maxTypeId.substring(parentId.length(),maxTypeId.length());
				}
				
				int typeIdEndNum = Integer.valueOf(maxTypeIdEndNum)+1;
				if (typeIdEndNum<10) {
					if(parentId.equals("0")){
						typeId =  "0"+typeIdEndNum;
					}else{
						typeId =  parentId+"0"+typeIdEndNum;
					}
				
					parameter.put("zoneCode", typeId);
				}else{
					if(parentId.equals("0")){
						typeId = ""+typeIdEndNum;
					}else{
						typeId = parentId+typeIdEndNum;
					}
					
					parameter.put("zoneCode", typeId);
				}
			}
			parameter.put("id", typeId);
			parameter.put("stateTime", new Date());
			parameter.put("levelDeep", parameter.get("zoneCode").toString().length()/2);
			ktZoneDao.create(parameter);
		}
	}

	@Override
	public List<Map<String, Object>> getSubOrg(Map parameter) {
		// TODO Auto-generated method stub
		String parentId = parameter.get("parentId") == null ? "0" : parameter.get("parentId").toString();
		 
		return ktOrgDao.getSubOrg(parentId);
	}

	@Override
	public PageDTO<Map<String, Object>> getOrgListByPage(Integer page, Integer pageSize, String filters) {
		// TODO Auto-generated method stub
		Long beginNum = (long) ((page - 1) * pageSize + 1);
		Long endNum = beginNum + pageSize - 1;

		List<Map<String,Object>> typeList = null;
		int recordCount = 0;
		String orgName = null;
		String parentId = null;
		String state = null;
		if(filters != null && !filters.trim().equals("")) {
			JSONObject jsonObject = JSONObject.fromObject(filters);
			JSONArray jsonArray = (JSONArray) jsonObject.get("rules");
			for(int i = 0; i < jsonArray.size(); i++) {
				JSONObject result = (JSONObject) jsonArray.get(i);
				if("orgName".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))){
					orgName =  result.getString("data");
				}
				if("parentId".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))){
					parentId =  result.getString("data");
				}
				if("state".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))){
					state =  result.getString("data");
				}
			}
		}
		
		typeList = ktOrgDao.getOrgListByPage(parentId,orgName,state,beginNum,endNum);
		recordCount = Integer.valueOf(ktOrgDao.getOrgListSize(parentId,orgName,state).get("total").toString());
		PageDTO<Map<String,Object>> result = new PageDTO<>(page, pageSize, typeList, recordCount);
		return result;
	}

	@Override
	public void saveOrg(Map parameter) {
		// TODO Auto-generated method stub
		String id = parameter.get("id") == null ? null : parameter.get("id").toString();
		String parentId =StringUtils.isNullOrEmpty(parameter.get("parentId")) ? "0": parameter.get("parentId").toString();
		if(!StringUtils.isNullOrEmpty(id)){
			//检查parentid 是否相同
				parameter.put("stateTime", new Date());
				ktOrgDao.update(parameter);
		}else{
			String typeId = null;
			Map maxData = ktOrgDao.getMaxData(parentId);
			if(maxData == null){
				if(parentId.equals("0")){
					typeId = "01";
					parameter.put("parentId", "0");
					parameter.put("orgCode", typeId);
				}else{
					typeId = parentId+"01";
					parameter.put("parentId", parentId);
					parameter.put("orgCode", typeId);
				}
				
			}else{
				String maxTypeId = maxData.get("orgCode").toString();
				
				String maxTypeIdEndNum = "0";
				if(parentId.equals("0")){
					parameter.put("parentId", "0");
					maxTypeIdEndNum = maxTypeId.substring(0,maxTypeId.length());
				}else{
					parameter.put("parentId", parentId);
					maxTypeIdEndNum = maxTypeId.substring(parentId.length(),maxTypeId.length());
				}
				
				int typeIdEndNum = Integer.valueOf(maxTypeIdEndNum)+1;
				if (typeIdEndNum<10) {
					if(parentId.equals("0")){
						typeId =  "0"+typeIdEndNum;
					}else{
						typeId =  parentId+"0"+typeIdEndNum;
					}
				
					parameter.put("orgCode", typeId);
				}else{
					if(parentId.equals("0")){
						typeId = ""+typeIdEndNum;
					}else{
						typeId = parentId+typeIdEndNum;
					}
					
					parameter.put("orgCode", typeId);
				}
			}
			parameter.put("id", typeId);
			parameter.put("stateTime", new Date());
			parameter.put("levelDeep", parameter.get("orgCode").toString().length()/2);
			ktOrgDao.create(parameter);
			
		}
	}

	@Override
	public PageDTO<Map<String, Object>> getUserListByPage(Integer page, Integer pageSize, String filters) {
		// TODO Auto-generated method stub
		Long beginNum = (long) ((page - 1) * pageSize + 1);
		Long endNum = beginNum + pageSize - 1;

		List<Map<String,Object>> typeList = null;
		int recordCount = 0;
		String username = null;
		String phone = null;
		String state = null;
		if(filters != null && !filters.trim().equals("")) {
			JSONObject jsonObject = JSONObject.fromObject(filters);
			JSONArray jsonArray = (JSONArray) jsonObject.get("rules");
			for(int i = 0; i < jsonArray.size(); i++) {
				JSONObject result = (JSONObject) jsonArray.get(i);
				if("username".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))){
					username =  result.getString("data");
				}
				if("phone".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))){
					phone =  result.getString("data");
				}
				if("state".equals(result.get("field")) && !StringUtils.isNullOrEmpty(result.getString("data"))){
					state =  result.getString("data");
				}
			}
		}
		
		typeList = platformUserDao.getUserListByPage(username,phone,state,beginNum,endNum);
		recordCount = Integer.valueOf(platformUserDao.getUserListSize(username,phone,state).get("total").toString());
		PageDTO<Map<String,Object>> result = new PageDTO<>(page, pageSize, typeList, recordCount);
		return result;
	}

	@Override
	public void saveUser(Map parameter) throws CustomException{
		// TODO Auto-generated method stub
		String id = parameter.get("id") == null ? null : parameter.get("id").toString();
		if(StringUtils.isNullOrEmpty(id)){
			String phone = parameter.get("phone").toString();
			UserDO userDO = userService.findUserByPhone(phone);
			if(userDO != null){
				throw new CustomException("用户: " + phone + " 已注册");
			}else{
				parameter.put("id", StringUtils.getUUID());
				parameter.put("state", "1");
				parameter.put("gmtCreate", new Date());
				parameter.put("isDelete",0);
				platformUserDao.create(parameter);
			}
		}else{
			parameter.put("gmtModified", new Date());
			platformUserDao.update(parameter);
		}
		
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveShop(Map parameter) throws CustomException {
		// TODO Auto-generated method stub
		String shopId = parameter.get("shopId") == null ? null : parameter.get("shopId").toString();
		String state = parameter.get("state") == null ? "" : parameter.get("state").toString();
		String userId = parameter.get("operator").toString();
		String mobile = parameter.get("mobile").toString();
//		Map clouderpUser = clouderpUserService.queryUserByMobile(mobile);
		Map clouderpUser = null;
		if(clouderpUser == null){
			//注册用户
			Map registerMap = new HashMap();
			registerMap.put("mobile", mobile);
			registerMap.put("userType", "002");
			registerMap.put("sid", StringUtils.getUUID());
			if (DEV_DEBUG) {
				registerMap.put("verifyCode","123456");
			}else{
				registerMap.put("verifyCode",DateUtil.formatDate(new Date(), "yyMMdd"));
			}
			
//			clouderpUser =clouderpUserService.register(registerMap);
			parameter.put("userId", clouderpUser.get("userId"));
		}else{
			parameter.put("userId", clouderpUser.get("userId"));
		}
		if(StringUtils.isNullOrEmpty(shopId)){
			
			parameter.put("createUser", userId);
			parameter.put("createTime", new Date());
			parameter.put("stateDate", new Date());
			
			dshopDao.create(parameter);
			dshopDao.createShopEmp(parameter.get("shopId").toString(), clouderpUser.get("userId").toString(), state);
			//创建店铺成员
		}else{
//			state = parameter.get("state") == null ? "" : parameter.get("state").toString();
			parameter.put("state",state);
			Map shopRecord = dshopDao.findById(Long.valueOf(shopId));
			if(!clouderpUser.get("userId").equals(shopRecord.get("userId"))){
				dshopDao.updateShopEmpUserId(shopId, shopRecord.get("userId").toString(), clouderpUser.get("userId").toString());
			}
			dshopDao.update(parameter);
			if(state.equals("") || state.equals("5")){
				state = "1";
			}
			dshopDao.updateShopEmpStatus(shopId, state);
			//修改店铺成员表状态
		}
	}

	@Override
	public List<Map<String, Object>> getShopList2User(Map parameter) {
		// TODO Auto-generated method stub
		String roleNo = parameter.get("roleNo").toString();
		String state = parameter.get("state") == null ? "" : parameter.get("state").toString();
		String zoneCode = parameter.get("zoneCode") == null ? "" : parameter.get("zoneCode").toString();
		String shopType = parameter.get("shopType") == null ? "" : parameter.get("shopType").toString();
		//如果当前用户是区域经理
		if("27".equals(roleNo)){
			return dshopDao.getShopList2User(zoneCode, null, state, shopType);
		}else{
			String userId = parameter.get("userId") == null ? "" : parameter.get("userId").toString();
			List<Map<String, Object>> data =  new ArrayList<Map<String,Object>>();
			if(!roleNo.equals("4") && !roleNo.equals("26") && !roleNo.equals("27")){
				if(roleNo.equals("1") || roleNo.equals("29")){
					data = dshopDao.getShopList2User(zoneCode, null, state, shopType);
				}else{
					data =  dshopDao.getShopList2User(zoneCode, userId, state, shopType); //
					Map centerMap = new HashMap();
					centerMap.put("shopId", "0");
					centerMap.put("shopName", "总部");
					data.add(0, centerMap);
				}
			}else{
				data =  dshopDao.getShopList2User(zoneCode, userId, state, shopType);   //店铺
			}
			return data;
		}
	}

	@Override
	public List<Map<String, Object>> getShopList2ZoneUser(Map parameter) {
		// TODO Auto-generated method stub
		String roleNo = parameter.get("roleNo").toString();
		String state = parameter.get("state") == null ? "" : parameter.get("state").toString();
		//如果当前用户是区域经理
		String zoneCode = parameter.get("zoneCode") == null ? "" : parameter.get("zoneCode").toString();
		String shopType = parameter.get("shopType") == null ? "" : parameter.get("shopType").toString();
		if("27".equals(roleNo)){
			return dshopDao.getShopList2ZoneUser(zoneCode, null, state,shopType);
		}else{
			String userId = parameter.get("userId") == null ? "" : parameter.get("userId").toString();
			List<Map<String, Object>> data =  new ArrayList<Map<String,Object>>();
			if(!roleNo.equals("4") && !roleNo.equals("26") && !roleNo.equals("27")){
				if(roleNo.equals("1") || roleNo.equals("29")){
					data = dshopDao.getShopList2ZoneUser(zoneCode, null, state,shopType);
				}else{
					data =  dshopDao.getShopList2ZoneUser(zoneCode, userId, state,shopType); //
					Map centerMap = new HashMap();
					centerMap.put("shopId", "0");
					centerMap.put("shopName", "总部");
					data.add(0, centerMap);
				}
			}else{
				data =  dshopDao.getShopList2ZoneUser(zoneCode, userId, state,shopType);   //店铺
			}
			return data;
		}
	}

	@Override
	public List<Map<String, Object>> getZoneList2User(Map parameter) {
		List<Map<String, Object>> data =  new ArrayList<Map<String,Object>>();
		String zoneCode = parameter.get("zoneCode") == null ? "" : parameter.get("zoneCode").toString();
		data = dshopDao.getZoneList2User(zoneCode);
		return data;
	}

	@Override
	public void saveInstock(Map parameter) {
		String prodList = parameter.get("prodList").toString();
		JSONArray dataArray = JSONArray.fromObject(prodList);

		for (int i = 0; dataArray.size() > 0 && i < dataArray.size(); i++) {
			JSONObject obj = dataArray.getJSONObject(i);
			Map instock = (Map) obj.toBean(obj, Map.class);
			instock.put("shopId", parameter.get("shopId"));
			double shortC = Double.parseDouble(instock.get("shortCode").toString());
			int shortCode = (new Double(shortC)).intValue();
			instock.put("shortCode", obj.get("shortCode"));
			Map prodMap = ktCommonMapper.selectProd(instock);
			if(prodMap != null){
				Map parame = new HashMap();
				parame.put("seqId", prodMap.get("SEQ_ID"));
				String stock = prodMap.get("STOCK").toString();
				String shopStockY = instock.get("shopStock").toString();
				String shopStock = prodMap.get("SHOP_STOCK") == null ? "0" : prodMap.get("SHOP_STOCK").toString();
				if(Double.parseDouble(shopStockY) * 10 + Double.parseDouble(shopStock) >= Double.parseDouble(stock)){
					parame.put("shopStock", stock);
				}else {
					parame.put("shopStock", Double.parseDouble(shopStockY) * 10 + Double.parseDouble(shopStock));
				}
				parame.put("repositoryStock", Double.parseDouble(stock) - Double.parseDouble(parame.get("shopStock").toString()));
				parame.put("stateDate", new Date());
				ktCommonMapper.updateShopProduct(parame);
			}
		}
	}
}
